import { getAttrs } from '../utils'
import merge from 'lodash/merge'
export default {
  props: {
    // 高亮行不触发勾选
    currentChangeDontSelect: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    checkboxConfig() {
      let param = {}
      if (!getAttrs(this, 'tree-config')) {
        param['range'] = true
      }
      return merge(param, getAttrs(this, 'checkboxConfig'))
    }
  },
  methods: {
    currentChange(params) {
      const { row } = params
      const checkConfig = getAttrs(this, `${this.selectionType}Config`)

      if (!this.currentChangeDontSelect) {
        const canCheck = checkConfig?.checkMethod
          ? checkConfig?.checkMethod?.({ row })
          : true
        if (this.selectionType === 'radio') {
          canCheck && this._setRadioRow(row)
        } else if (this.selectionType === 'checkbox') {
          if (canCheck) {
            this._clearCheckboxRow()
            this._setCheckboxRow(row, true)
          }
        }
      }

      this.$emit('current-change', params)
    },
    /**
     * @param isTips {Boolean} 是否显示提示信息
     * @param isReserve {Boolean} 包含已保留选中的行数据
     */
    getSelections(isTips, isReserve) {
      if (this.selectionType === null) return null
      const config = getAttrs(this, `${this.selectionType}-config`)
      if (isReserve && !config?.reserve) {
        throw new Error(
          `如果想获取已保留选中的行数据，请开启 ${this.selectionType}-config.reserve`
        )
      }

      let selectedData = []
      let getRecordMethod = () => []
      let getReserveMethod = () => []

      const isCheckbox = this.selectionType === 'checkbox'

      if (isCheckbox) {
        getRecordMethod = this._getCheckboxRecords
        isReserve && (getReserveMethod = this._getCheckboxReserveRecords)
      } else {
        getRecordMethod = () => [this._getRadioRecord()].filter(Boolean)
        isReserve &&
          (getReserveMethod = () =>
            [this._getRadioReserveRecord()].filter(Boolean))
      }

      selectedData.push(...getRecordMethod())
      selectedData.push(...getReserveMethod())

      // if (isTips && !selectedData.length) {
      //   this.$sxMessage({
      //     message: '请选择至少一条记录',
      //     type: 'warning'
      //   })
      //   return null
      // }
      return selectedData
    },
    //清除表格选中行
    clearSelection() {
      if (this.selectionType === 'radio') {
        this.tableNode.clearRadioRow()
      } else {
        this.tableNode.clearCheckboxRow()
        // 清除保留选中 reserve的内部状态
        const config = getAttrs(this, `checkbox-config`)
        if (config?.reserve) {
          this.tableNode.clearCheckboxReserve()
        }
      }
    }
  }
}
